package com.blate.dogxiao.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blate.dogxiao.R;
import com.blate.dogxiao.adapter.CitySelectorAdapter;
import com.blate.dogxiao.adapter.SimpleDataRecyclerViewAdapter;
import com.blate.dogxiao.bean.CityInfo;
import com.blate.dogxiao.databinding.ActivityCitySelectorBinding;
import com.blate.dogxiao.databinding.ItemCitySelectorCityItemBinding;
import com.blate.dogxiao.decoration.CityListDecoration;
import com.blate.dogxiao.function.AutoIoScheduler;
import com.github.promeg.pinyinhelper.Pinyin;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * 城市选择
 *
 * @author Az
 * on 2020/10/22
 */
public class CitySelectorActivity
        extends AppCompatActivity {

    private ActivityCitySelectorBinding mBinding;

    private CitySelectorAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_city_selector);
        initialize();
    }

    private void initialize() {
        mBinding.topBar.setNavigationOnClickListener(v -> finish());

        mBinding.rvCities.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mBinding.rvCities.addItemDecoration(new CityListDecoration(this));
        mAdapter = new CitySelectorAdapter();
        mAdapter.setItemChildClickListener(
                new SimpleDataRecyclerViewAdapter.MonitorViewCollector<ItemCitySelectorCityItemBinding>() {
                    @Override
                    public void collectorMonitorView(SimpleDataRecyclerViewAdapter.ItemViewMonitor itemViewMonitor, ItemCitySelectorCityItemBinding binding) {
                        itemViewMonitor.monitorView(binding.getRoot());
                    }
                },
                new SimpleDataRecyclerViewAdapter.OnItemChildClickListener<ItemCitySelectorCityItemBinding, Pair<String, CityInfo>>() {
                    @Override
                    public void onItemChildClick(ItemCitySelectorCityItemBinding binding, View view, Pair<String, CityInfo> data) {
                        Intent intent = new Intent();
                        intent.putExtra("city", data.second.cityName);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
        );
        mBinding.rvCities.setAdapter(mAdapter);

        mBinding.bivCitiesIndex.setOnIndexChangeListener(words -> {
            RecyclerView.LayoutManager layoutManager = mBinding.rvCities.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                if ("#".equals(words)) {
                    linearLayoutManager.scrollToPositionWithOffset(0, 0);
                    return;
                }
                RecyclerView.Adapter<?> adapter = mBinding.rvCities.getAdapter();
                if (adapter instanceof CitySelectorAdapter) {
                    linearLayoutManager.scrollToPositionWithOffset(((CitySelectorAdapter) adapter).getIndexByKey(words), 0);
                }
            }
        });

        loadCities();
    }

    public void loadCities() {
        Observable.fromCallable(new Callable<List<CityInfo>>() {
            @Override
            public List<CityInfo> call() throws Exception {
                AssetManager assetManager = getApplicationContext().getAssets();
                try (InputStream inputStream = assetManager.open("cities.json")) {
                    Type stringList = new TypeToken<ArrayList<CityInfo>>() {
                    }.getType();
                    return new Gson().fromJson(new InputStreamReader(inputStream), stringList);
                }
            }
        })
                .map(new Function<List<CityInfo>, List<Pair<String, CityInfo>>>() {
                    @Override
                    public List<Pair<String, CityInfo>> apply(@NonNull List<CityInfo> strings) throws Exception {
                        List<Pair<String, CityInfo>> result = new ArrayList<>();
                        for (CityInfo cityInfo : strings) {
                            result.add(new Pair<>(Pinyin.toPinyin(cityInfo.cityName, ""), cityInfo));
                        }
                        return result;
                    }
                })
                .compose(new AutoIoScheduler<>())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new Consumer<List<Pair<String, CityInfo>>>() {
                    @Override
                    public void accept(List<Pair<String, CityInfo>> strings) throws Exception {
                        mAdapter.putData(true, strings);
                    }
                });
    }

}

